package com.zzzy.doc.service.exchange;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzzy.common.exception.WarningException;
import com.zzzy.common.util.AssertUtil;
import com.zzzy.common.util.CglibBeanCopierUtil;
import com.zzzy.common.util.FileUtil;
import com.zzzy.common.util.MyBatisUtils;
import com.zzzy.common.vo.PageResult;
import com.zzzy.doc.common.enums.DocReceiveStatusEnum;
import com.zzzy.doc.common.enums.UrgencyEnum;
import com.zzzy.doc.dao.entity.DocFile;
import com.zzzy.doc.dao.entity.DocReceiveRecord;
import com.zzzy.doc.dao.entity.Document;
import com.zzzy.doc.dao.mapper.DocReceiveRecordMapper;
import com.zzzy.doc.service.DocFileService;
import com.zzzy.doc.service.DocService;
import com.zzzy.doc.vo.document.DocBasicInfoRes;
import com.zzzy.doc.vo.document.DocInfoRes;
import com.zzzy.doc.vo.document.exchange.receive.DocExchangeReceivePageReq;
import com.zzzy.doc.vo.document.exchange.receive.DocExchangeReceiveQueryRes;
import com.zzzy.doc.vo.pageoffice.OpenOfficeFileRes;
import com.zzzy.framework.common.dict.DictService;
import com.zzzy.framework.common.enums.sys.DataScopeEnum;
import com.zzzy.framework.common.util.PageOfficeUtil;
import com.zzzy.framework.common.util.SecurityUtils;
import com.zzzy.framework.common.util.SortFieldUtil;
import com.zzzy.framework.dto.DataPermissionDto;
import com.zzzy.sys.api.DeptApi;
import com.zzzy.sys.dto.DeptInfoDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 单位收文记录
 *
 * @author fc
 * @since 2024-09-09
 */
@Service
public class DocReceiveRecordService extends ServiceImpl<DocReceiveRecordMapper, DocReceiveRecord> {

    @Resource
    protected DictService dictService;
    @Resource
    private DocService docService;
    @Resource
    private DocFileService docFileService;
    @Resource
    protected DeptApi deptService;

    public List<DocExchangeReceiveQueryRes> getReceiveListBySendId(Long sendId) {
        return baseMapper.selectListBySendId(sendId);
    }
    public DocExchangeReceiveQueryRes getReceiveByReceiveId(Long receiveId) {
        DocExchangeReceiveQueryRes receiveQueryRes = baseMapper.selectByReceiveId(receiveId);
        AssertUtil.nonNull(receiveQueryRes, "单位收文记录不存在");
        DataPermissionDto dataPermissionDto = SecurityUtils.getLoginUser().getDataPermissionDto();
        //当前用户为全部数据权限
        if (DataScopeEnum.ALL.getValue().equals(dataPermissionDto.getDataPermission())){
            return receiveQueryRes;
        }
        Set<Long> userIdSet = dataPermissionDto.getUserIdSet();
        if (userIdSet.contains(receiveQueryRes.getReceiveUserId())){
            return receiveQueryRes;
        }
        throw new WarningException("当前用户无此数据查看权限");
    }

    public PageResult<DocExchangeReceiveQueryRes> getPage(DocExchangeReceivePageReq queryReq) {

        IPage<DocExchangeReceiveQueryRes> mpPage = MyBatisUtils.buildPage(queryReq, SortFieldUtil.getSortingFields(DocExchangeReceiveQueryRes.class, queryReq.getOrderField(), queryReq.getOrderRule()));
        mpPage = baseMapper.selectPage(mpPage, queryReq, SecurityUtils.getLoginUser().getId());
        Map<Object, String> urgencyMap = dictService.getDictDataMap(UrgencyEnum.class);
        mpPage.getRecords().forEach(doc -> doc.setUrgencyDescription(urgencyMap.get(doc.getUrgency())));
        return new PageResult<>(mpPage);
    }

    public DocReceiveRecord getByIdForQuery(Long id) {
        DocReceiveRecord receiveRecord = baseMapper.selectById(id);
        AssertUtil.nonNull(receiveRecord, "单位收文记录不存在");
        DataPermissionDto dataPermissionDto = SecurityUtils.getLoginUser().getDataPermissionDto();
        //当前用户为全部数据权限
        if (DataScopeEnum.ALL.getValue().equals(dataPermissionDto.getDataPermission())){
            return receiveRecord;
        }
        Set<Long> userIdSet = dataPermissionDto.getUserIdSet();
        if (userIdSet.contains(receiveRecord.getReceiveUserId())){
            return receiveRecord;
        }
        throw new WarningException("当前用户无此数据查看权限");
    }

    public DocBasicInfoRes getDocBasicInfo(Long id) {
        DocReceiveRecord receiveRecord = getByIdForQuery(id);
        Document document = docService.getDocById(receiveRecord.getDocId());
        document.setDocThumbnailBlob(null);
        DocBasicInfoRes docBasicInfoRes = CglibBeanCopierUtil.copy(document, DocBasicInfoRes.class);
        List<Long> mainSendUnitIdList = StringUtils.isBlank(document.getMainSendUnitIds()) ? Collections.emptyList()
                : Arrays.stream(docBasicInfoRes.getMainSendUnitIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<DeptInfoDto> mainSendUnitList = deptService.getDeptDtoList(mainSendUnitIdList);
        List<Long> copySendUnitIdList = StringUtils.isBlank(document.getCopySendUnitIds()) ? Collections.emptyList()
                : Arrays.stream(docBasicInfoRes.getCopySendUnitIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<DeptInfoDto> copySendUnitList = deptService.getDeptDtoList(copySendUnitIdList);
        docBasicInfoRes.setMainSendUnitList(mainSendUnitList);
        docBasicInfoRes.setMainSendUnit(mainSendUnitList.stream().map(DeptInfoDto::getName).collect(Collectors.joining(",")));
        docBasicInfoRes.setCopySendUnitList(copySendUnitList);
        docBasicInfoRes.setCopySendUnit(copySendUnitList.stream().map(DeptInfoDto::getName).collect(Collectors.joining(",")));
        return docBasicInfoRes;
    }

    public OpenOfficeFileRes getFinalPageOfficeResByDocId(Long id, String openFileUrl) {
        DocReceiveRecord receiveRecord = getByIdForQuery(id);
        Document document = docService.getDocById(receiveRecord.getDocId());
        String fileName = document.getSubject() + "." + FileUtil.PDF;
        String pdfReadOnlyHtml = PageOfficeUtil.getPdfHtml(openFileUrl, fileName);
        return OpenOfficeFileRes.builder().html(pdfReadOnlyHtml).pdf(true).build();
    }
    public DocInfoRes getDocInfo(Long id) {
        DocReceiveRecord receiveRecord = getByIdForQuery(id);
        DocFile docFile = docFileService.getDocFileByDocId(receiveRecord.getDocId());
        DocInfoRes docInfoRes = CglibBeanCopierUtil.copy(docFile, DocInfoRes.class);
        Document document = docService.getDocById(receiveRecord.getDocId());
        CglibBeanCopierUtil.copy(document, docInfoRes);
        return docInfoRes;
    }

    public void confirmReceive(Long id) {
        DocReceiveRecord receiveRecord = getByIdForQuery(id);
        AssertUtil.isEquals(DocReceiveStatusEnum.TO_BE_RECEIVED.getValue(), receiveRecord.getStatus(), "当前状态不是待签收，无法签收");
        AssertUtil.isEquals(SecurityUtils.getLoginUser().getId(), receiveRecord.getReceiveUserId(), "当前签收人不是本人，无法签收");
        receiveRecord.setStatus(DocReceiveStatusEnum.RECEIVED.getValue());
        receiveRecord.setConfirmReceiveTime(LocalDateTime.now());
        baseMapper.updateById(receiveRecord);
    }

    public boolean isConfirmReceive(Long id) {
        DocReceiveRecord receiveRecord = getByIdForQuery(id);
        return DocReceiveStatusEnum.TO_BE_RECEIVED.getValue().equals(receiveRecord.getStatus())
                && SecurityUtils.getLoginUser().getId().equals(receiveRecord.getReceiveUserId());
    }
}
